# cython: language_level=3
from collections import defaultdict
import json
import logging
import time
import numpy as np
import pandas as pd
from sanic.views import HTTPMethodView

from utils.decorators import param_check
from utils.response import general_json_res
from .utils import process_phone_number
import app.model_vn.model_main as model_main
import app.model_vn.cal_app_features as app
import app.model_vn.cal_sms_features as sms
# import app.model_vn.cal_device_features as device
import app.model_vn.model_predict as md
from app.model_phl import utils


class Predict(HTTPMethodView):
    """restful接口实例"""

    async def get(self, request, pk=0):
        return general_json_res(404, "no get method.")

    @param_check(
        {
            "Phone",
            "ApplyNO",
        }
    )
    async def post(self, request, pk=0):
        Phone = request.json.get("Phone")
        phone_sub = request.json.get("phone_sub")
        ApplyNO = request.json.get("ApplyNO")
        # 根据手机号和订单号直接拿数据算评分
        free_features = model_main.get_free_features(phone_sub, ApplyNO)
        # obj = await DemoUser.create(name=name)
        return general_json_res(result=free_features)

    # async def post(self, request, pk=0):
    #     Phone = request.json.get("Phone")
    #     ApplyNO = request.json.get("ApplyNO")
    #     print(Phone)
    #     # 处理手机号码
    #     phone_sub = process_phone_number(Phone)
    #     # 根据手机号和订单号直接拿数据算评分
    #     free_features = model_main.get_free_features(phone_sub, ApplyNO)
    #     # obj = await DemoUser.create(name=name)
    #     return general_json_res(result=free_features)

class GetScore(HTTPMethodView):
    async def get(self, request, pk=0):
        return general_json_res(404, "no get method.")

    async def post(self, request, pk=0):
        Phone = request.json.get("Phone")
        phone_sub = request.json.get("phone_sub")
        ApplyNO = request.json.get("ApplyNO")

        # 指标
        Isrenew = request.json.get("Isrenew")
        in_white_list = request.json.get("in_white_list")
        UserInfo = request.json.get("UserInfo")
        params = request.json
        AppList = request.json.get("AppList")
        AppType = request.json.get("AppType")
        SmsList = request.json.get("SmsList")
        DeviceList = request.json.get("deviceInfo", {})
        free_features = request.json.get("free_features", {})
        
        # 1 age
        if UserInfo is None:
            UserInfo = {}
        cal_userinfo_features = {
            'age': UserInfo.get('age', None),
            'Birthday': UserInfo.get('Birthday', None),
            'in_white_list': in_white_list,
            'Education': UserInfo.get('Education', None),
        }
        free_features.update(cal_userinfo_features)

        # 协程加速 同时计算app、device和sms
        async def appFunction(AppList, AppType):
            AppList = pd.DataFrame(AppList)
            AppType = pd.DataFrame(AppType)
            app_features2 = app.calculateFreeAppFeatures(AppList, AppType)
            return app_features2
        async def smsFunction(SmsList):
            SmsList = pd.DataFrame(SmsList)
            sms_features = sms.calculate_sms_features(SmsList)
            return sms_features


        async def my_view(free_features, AppList, AppType, SmsList):
            app_features2 = await appFunction(AppList, AppType)
            sms_features = await smsFunction(SmsList)
            free_features.update(app_features2)
            free_features.update(sms_features)
            return free_features

        free_features = await my_view(free_features, AppList, AppType, SmsList)

        # 4 用户评分模块
        model_score_features = md.get_user_model_score_main(free_features)
        free_features.update(model_score_features)

        # 5 基于指标库和评分模型按着分支驱动决策引擎，进行风控决策
        start = time.time()
        ruleResult = {
            'CreditScore': model_score_features['creditScoreV1'],
            'OldCreditScore': model_score_features['creditScoreV1'],
        }
        end = time.time()
        running_time = end - start
        # print('决策模块耗费时间 : %.5f 秒' % running_time)

        # obj = await DemoUser.create(name=name)

        # 遍历字典中的每个值，并将np.nan替换为None
        for key, value in free_features.items():
            if isinstance(value, float) and np.isnan(value):
                free_features[key] = None

        result = {}
        result['free_features'] = free_features
        result['free_rule'] = ruleResult
        
        return general_json_res(result=result)


class Model(HTTPMethodView):
    """restful接口实例"""

    async def get(self, request, pk=0):
        return general_json_res(404, "no get method.")

    # @param_check(
    #     {
    #         "Phone",
    #         "ApplyNO",
    #     }
    # )
    async def post(self, request, pk=0):
        free_features = request.json
        # 4 用户评分模块
        model_score_features = md.get_user_model_score_main(free_features)
        free_features.update(model_score_features)
        # obj = await DemoUser.create(name=name)
        return general_json_res(result=free_features)